//岛屿数量
class Solution {
public:
    vector<vector<bool>> hash;
    int dx[4] = {0, 0, 1, -1};
    int dy[4] = {1, -1, 0, 0};
    typedef pair<int, int> PII;
    int numIslands(vector<vector<char>>& grid) {
        // char target = '1';
        int m = grid.size();
        int n = grid[0].size();
        int ret = 0;
        hash.resize(m, vector<bool>(n, false));
        queue<PII> q;
        // q.push(grid[0][0]);
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == '0' || hash[i][j])
                    continue;
                q.push({i, j});
                hash[i][j] = true;
                ret++;
                while (q.size()) {
                    auto [a, b] = q.front();
                    q.pop();
                    for (int k = 0; k < 4; k++) {
                        int x = a + dx[k];
                        int y = b + dy[k];
                        if (x >= 0 && x < m && y >= 0 && y < n &&
                            grid[x][y] == '1' && hash[x][y] == false) {
                            hash[x][y] = true;
                            q.push({x, y});
                        }
                    }
                }
            }
        }
        return ret;
    }
};

//岛屿的最大面积
class Solution {
public:
    int m, n;
    vector<vector<bool>> vis;
    int dx[4] = {0, 0, 1, -1};
    int dy[4] = {1, -1, 0, 0};
    typedef pair<int, int> PII;
    int maxAreaOfIsland(vector<vector<int>>& grid) {
        m = grid.size();
        n = grid[0].size();
        vis.resize(m, vector<bool>(n, false));
        int ret = 0;
        int count;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] && !vis[i][j]) {
                    count = bfs(grid, i, j);
                    ret = max(ret, count);
                }
            }
        }
        return ret;
    }
    int bfs(vector<vector<int>> grid, int i, int j) {
        queue<PII> q;
        q.push({i, j});
        vis[i][j] = true;
        int ret = 0;
        while (q.size()) {
            auto [a, b] = q.front();
            ret++;
            q.pop();
            for (int k = 0; k < 4; k++) {
                int x = a + dx[k];
                int y = b + dy[k];
                if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] &&
                    !vis[x][y]) {
                    vis[x][y] = true;
                    q.push({x, y});
                }
            }
        }
        return ret;
    }
};